package controllers

import (
	"animals/cache"
	"animals/models"
	"animals/pkg"
	beego "github.com/beego/beego/v2/server/web"
	"time"
)

type UserMainController struct {
	beego.Controller
}

type Res1 struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *UserMainController) Register() {
	username := c.GetString("username")
	password := c.GetString("password")
	var user models.User
	user.Username = username
	user.Password = password
	if password == "" || username == "" {
		c.Data["json"] = Res1{
			Code: 400,
			Msg:  "参数为空",
			Data: nil,
		}
		c.ServeJSON()
	}
	err := models.DB.Create(&user).Error
	if err != nil {
		c.Data["json"] = Res1{
			Code: 400,
			Msg:  "注册失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = Res1{
			Code: 400,
			Msg:  "注册成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}

func (c *UserMainController) Login() {
	username := c.GetString("username")
	password := c.GetString("password")
	var user models.User
	pwd := pkg.Md5(password)
	user.Username = username
	user.Password = pwd
	if password == "" || username == "" {
		c.Data["json"] = Res1{
			Code: 400,
			Msg:  "参数为空",
			Data: nil,
		}
		c.ServeJSON()
	}
	err := models.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.Data["json"] = Res1{
			Code: 400,
			Msg:  "登录失败",
			Data: nil,
		}
		c.ServeJSON()
	}
	key := "user_login" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, key).Int()
	if errCount >= 3 {
		c.Data["json"] = Res1{
			Code: 400,
			Msg:  "密码错误过多",
			Data: nil,
		}
		c.ServeJSON()
	}
	if user.Username == pkg.Md5(password) {
		cache.Rdb.Expire(cache.Ctx, key, time.Hour*2)

	}
	cache.Rdb.Incr(cache.Ctx, key)
	c.Data["json"] = Res1{
		Code: 400,
		Msg:  "登录成功",
		Data: nil,
	}
	c.ServeJSON()
}
